<template>
  <div class="app-container bg-gray">
    <el-row class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <el-button type="success" class="bg-green" icon="el-icon-circle-plus" @click="toAdd">添加部门</el-button>
            <div>
              <el-input v-model="searchTerms.searchValue" placeholder="请输入内容" class="search-input" @change="getData"/>
              <el-button type="success" class="bg-green" icon="el-icon-search" @click="getData">搜索</el-button>
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" width="100" header-align="center" align="center" sortable />
            <el-table-column prop="name" label="部门名称" min-width="220" header-align="center" align="center" />
            <el-table-column prop="departmentName" label="企业微信部门（id）" min-width="160" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row.departmentName?(scope.row.departmentName+'（'+scope.row.wechat_channel_id+'）') : '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" min-width="140" header-align="center" align="center" sortable />
            <el-table-column prop="updated_at" label="更新时间" min-width="140" header-align="center" align="center" sortable />
            <el-table-column label="操作" width="200" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button type="success" size="small" icon="el-icon-edit" circle class="bg-green" @click="toEdit(scope.row)" />
                <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :title="form.title" width="550px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" autofocus/>
        </el-form-item>
        <el-form-item label="企业微信对应部门">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">选择部门</el-radio>
            <el-radio :label="2">同步创建</el-radio>
            <el-radio :label="3">不关联</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type!==3" :label="form.type===1?'对应部门':'父级部门'" prop="wechat_channel_id">
          <el-select v-model="form['wechat_channel_id']" placeholder="请选择对应的部门">
            <el-option v-for="item in qyDepartmentList" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" :disabled="loading" type="primary" @click="submitDialog('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime } from '../../utils/table';

export default {
  data() {
    return {
      loading: false,
      searchTerms: {
        searchValue: ''
      },
      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,
      // 表格相关参数
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: [],

      // 弹出框相关数据
      dialogVisible: false,
      // 企业微信部门列表
      qyDepartmentList: [],
      form: {
        title: '',
        name: '',
        type: 1,
        wechat_channel_id: ''
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'change' }]
      }
    }
  },
  watch: {},
  created() {
    this.getData();
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime,
    getData(order) {
      this.tableLoading = true;
      order || (order = {});
      const url = 'company/list';
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue
      };
      order.sortName && (data.sortName = order.sortName);
      order.sortOrder && (data.sortOrder = order.sortOrder);
      this.$store.dispatch('GetConnect', {url, data}).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
        this.tableLoading = false;
        this.loadQyDepartment();
      }).catch(e => {
        this.tableLoading = false;
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    // 获取企业微信部门
    loadQyDepartment() {
      const url = 'company/getDepartmentList';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.qyDepartmentList = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    /**
     * 添加部门弹出框和修改部门弹出窗
     * row: 当前行的数据
     */
    toAdd() {
      this.form = {
        type: 1
      };
      this.dialogVisible = true;
      this.form.title = '添加部门';
    },
    toEdit(row) {
      this.dialogVisible = true;
      this.form = Object.assign({type: 1, title: '编辑部门'}, row);
    },

    /**
     * 弹窗表单提交方法,通过判断有没有form_id执行添加或编辑操作
     * formName: form表单中ref的值,即表单名
     */
    submitDialog(formName) {
      this.$refs[formName].validate((valid) => { // 表单验证
        if (valid) {
          this.loading = true;
          const url = this.form.id ? '/company/edit/' + this.form.id : '/company/create';
          const data = this.form;
          data.type === 2 && (data.parent_id = data.wechat_channel_id);
          this.$store.dispatch('GetConnect', {url, data}).then(res => {
            this.dialogVisible = false;
            this.$message.success(res.msg);
            this.getData();
            this.loading = false;
          }).catch(e => {
            this.$message.error(e.msg);
            this.loading = false;
          })
          // this.$confirm('此操作将会把该部门里的所有人转移到新选择的部门中', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          //   const url = this.form.id ? '/company/edit/' + this.form.id : '/company/create';
          //   const data = this.form;
          //   this.$store.dispatch('GetConnect', {url, data}).then(res => {
          //     this.dialogVisible = false;
          //     this.$message.success(res.msg);
          //     this.getData();
          //   }).catch(e => {
          //     this.$message.error(e.msg);
          //   })
          // })
        }
      })
    },
    /*
      * 表单查询条件重置方法,清除数据及验证信息
      * formName: form表单中ref的值,即表单名
      */
    resetDialog(formName) {
      this.$refs[formName].resetFields();
    },

    /*
       * 删除部门
       * row: 当前行的数据
       */
    toDelete(row) {
      this.$confirm('此操作将删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = '/company/delete/' + row.id;
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch(e => {
          this.$message.error(e.msg);
        })
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../styles/index.scss';
  .box-1 {
    .header {
      @include flex-row(center, space-between);
      padding-bottom: 15px;
      .search-input {
        width: 240px;
      }
    }
  }

  .dialog {
    .el-input {
      width: 80%;
    }
  }
</style>
